/*
 * @Description: 
 * @Version: 
 * @Company: 杭州凯立通信有限公司
 * @Author: Jesen
 * @Date: 2018-11-22 17:50:51
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2018-11-26 11:36:09
 */
import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '../store'
import Cookies from 'js-cookie'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import whiteList from './directAccess'
import asyncRouter from './asyncRouter'

// 页面刷新时，重新赋值token
if (Cookies.get('token')) {
    store.dispatch('user/relogin')
}
NProgress.configure({ showSpinner: false });
Vue.use(VueRouter)

/**
 * 根据权限匹配路由
 * @param {array} permission 权限列表（菜单列表）
 * @param {array} asyncRouter 异步路由对象
 */
function routerMatch(permission, asyncRouter) {
    return new Promise((resolve) => {
        const routers = asyncRouter[0]
            // 创建路由
        function createRouter(permission) {
            permission.forEach((item) => {
                if (item.subs && item.subs.length) {
                    // 递归
                    createRouter(item.subs)
                }
                let path = '/' + item.index
                    // 循环异步路由，将符合权限列表的路由加入到routers中
                asyncRouter.find(function(s) {
                    if (s.path == path) {
                        s.meta.permission = item.permission
                        routers.children.push(s)
                        return
                    }
                })
            })
        }

        createRouter(permission)
        resolve([routers])
    })
}


// 默认路由表，不需要权限
const routes = [{
        path: '/',
        redirect: '/dashboard'
    },
    {
        path: '/',
        component: r => require.ensure([], () => r(require('../components/common/Home.vue')), 'home'),
        meta: { title: '自述文件' },
        children: [{
                path: '/dashboard',
                component: r => require.ensure([], () => r(require('../components/page/Dashboard')), 'dashboard'),
                meta: { title: '系统首页' }
            },
            {
                path: '/404',
                component: r => require.ensure([], () => r(require('../components/page/404')), '404'),
                meta: { title: '404' }
            },
            {
                path: '/403',
                component: r => require.ensure([], () => r(require('../components/page/403')), '403'),
                meta: { title: '403' }
            }
        ]
    },
    {
        path: '/login',
        component: resolve => require(['../components/page/Login.vue'], resolve)
    },
    {
        path: '*',
        redirect: '/404'
    }
]


const router = new VueRouter({
    mode: 'history',
    routes: routes
})

// 路由跳转前验证
router.beforeEach((to, from, next) => {
    debugger
    // 简单的判断IE10及以下不进入，不兼容
    if (navigator.userAgent.indexOf('MSIE') > -1 && to.path) {
        Vue.prototype.$alert('vue系统不兼容IE10及以下浏览器，请使用更高版本的浏览器查看', '浏览器不兼容通知', {
            confirmButtonText: '确定'
        });
    } else {
        // 开启进度条
        NProgress.start();

        // 判断用户是否登录
        if (Cookies.get('token')) {
            // 如果当前处于登录状态，并且跳转地址为login，则自动跳回系统首页
            // 这种情况出现在手动修改地址栏地址时
            if (to.path === '/login') {
                router.replace('/dashboard')
            } else {
                // 页面跳转前先判断是否存在权限列表，如果存在则直接跳转，如果没有则请求一次
                if (store.state.permission.list.length === 0) {
                    // 获取权限列表，如果失败则跳回登录页重新登录
                    store.dispatch('permission/getPermission').then(res => {
                        // 匹配并生成需要添加的路由对象
                        routerMatch(res, asyncRouter).then(res => {
                            console.log(res)
                            router.addRoutes(res)
                            console.log(router)
                            next(to.path)
                        })
                    }).catch(() => {
                        console.log('登录错误')
                        store.dispatch('user/logout').then(() => {
                            router.replace('/login')
                        })
                    })
                } else {
                    // 如果跳转页面存在于路由中则进入，否则跳转到404
                    // 因为可以通过改变url值进行访问，所以必须有该判断
                    if (to.matched.length) {
                        if (whiteList.indexOf(to.path) < 0) {
                            // store.dispatch('user/actionlog', to)
                        }
                        next()
                    } else {
                        router.replace('/error/404')
                    }
                }
            }
        } else {
            // 如果是免登陆的页面则直接进入，否则跳转到登录页面
            if (whiteList.indexOf(to.path) >= 0) {
                console.log('该页面无需登录即可访问')
                next()
            } else {
                console.log('请重新登录')
                router.replace('/login')
                NProgress.done()
            }
        }
    }
})

router.afterEach(() => {
    NProgress.done(); // 结束Progress
})

export default router